/**
 * Created by Administrator on 2017/8/11 0011.
 */
function BomPropertyList(element, value_rule, property_id) {
    this.Element = element;
    this.ValueRule = value_rule;
    this.PropertyId = property_id;
}

BomPropertyList.prototype = {
    render: function () {
        $("#is_new_add_a").remove();
        $("#property_table_list").remove();

        this.Element.empty();
        // new_value_rule = this.ValueRule;
        // new_property_id = this.PropertyId;

        var html = '';

        html += '<a type="button" class="btn btn-primary add-icon attribute-search-btn" id="proper-list-search-btn"><div class="btn-icon"></div><div class="btn-text">查询</div></a>';
        html += '<div class="form-horizontal"><div class="form-group">';
        html += '<div class="col-lg-3"><input type="text" class="form-control" id="table-name" placeholder="表名" value=""></div>';
        html += '<div class="col-lg-3"><input type="text" class="form-control" id="column-key" placeholder="字段名称" value=""></div>';
        html += '<div class="col-lg-3"><input type="text" class="form-control" id="column-name" placeholder="显示名称" value=""></div>';
        html += '<div class="col-lg-3"><input type="text" class="form-control" id="table-where" placeholder="过滤条件"></div>';
        html += '</div></div>';
        html += '<table class="table table-bordered table-hover" id="bom-property-rule-list-table">';
        html += '<thead></thead>';
        html += '<tbody></tbody>';
        html += '</table>';

        var obj = $(html);
        this.Element.append(obj);

        var that = this;
        //绑定数据
        if (this.ValueRule) {
            var table_name = this.ValueRule.table_name;
            this.Element.find("#table-name").val(table_name);

            var table_where = this.ValueRule.where;
            this.Element.find("#table-where").val(table_where);

            var column_key = "";
            var column_name = "";
            for (var i = 0; i < this.ValueRule.columns.length; i++) {
                var column = this.ValueRule.columns[i];
                column_key += column["key"];
                column_name += column["name"];
                if (i != this.ValueRule.columns.length - 1) {
                    column_key += ",";
                    column_name += ",";
                }
            }

            this.Element.find("#column-key").val(column_key);
            this.Element.find("#column-name").val(column_name);

            if (!this.ValueRule.IsEdit) {
                var value_ids = new Array();
                var data1 = {};
                data1.property_id = this.PropertyId;
                requestJson('../product-bom/get-property-list-value-relation', data1, false, function (response) {
                    if (response.status == 0) {
                        if (response.data) {
                            for (var i = 0; i < response.data.length; i++) {
                                value_ids.push(response.data[i]);
                            }
                        }
                    }
                });

                this.ValueRule.value_ids = value_ids;
            }
            if (this.ValueRule.value_ids) {
                var data = {};
                data.table_name = table_name;
                data.columns = column_key;
                data.where = table_where;

                requestJson('../product-bom/get-datas-by-talbe-name-handler', data, true, function (response) {
                    if (response.status == 0) {
                        var thead = that.Element.find("thead");
                        var tbody = that.Element.find("tbody");
                        thead.empty();
                        tbody.empty();
                        var html_thead = '<tr><th><input type="checkbox" class="check-box" id="checkAll"></th>';

                        var names = that.Element.find("#column-name").val().split(",");
                        var keys = that.Element.find("#column-key").val().split(",");
                        for (var i = 0; i < names.length; i++) {
                            var name = names[i];
                            if (name.toLowerCase() != "id") {
                                html_thead += "<th>" + name + "</th>";
                            }
                        }

                        html_thead += "</tr>";

                        thead.append($(html_thead));

                        for (var i = 0; i < response.data.length; i++) {
                            var item = response.data[i];
                            var html_tbody = '';
                            html_tbody += '<tr>';
                            var check_str = "";
                            for (var j = 0; j < that.ValueRule.value_ids.length; j++) {
                                var value_id = that.ValueRule.value_ids[j];
                                if (value_id == item["id"]) {
                                    check_str = 'checked="checked"';
                                    check_str += ' onclick="return false"';
                                    break;
                                }
                            }

                            var chk = '';
                            chk = '<td><input type="checkbox" class="check-box" ' + check_str + ' name="list-checkbox" ';
                            for (var j = 0; j < that.ValueRule.columns.length; j++) {
                                var column = that.ValueRule.columns[j];
                                chk += ' data-' + column.key + '="' + item[column.key] + '"';
                            }

                            if (item['url'] != undefined) {
                                chk += ' data-url="' + item['url'] + '"';
                            }

                            chk += '></td>';

                            var td = '';
                            for (var j = 0; j < keys.length; j++) {
                                if (keys[j].toLowerCase() != "id") {
                                    td += '<td>' + item[keys[j]] + '</td>';
                                }
                            }

                            html_tbody += chk + td + '</tr>';
                            tbody.append($(html_tbody));
                        }

                        that.Element.find("#checkAll").click(function () {
                            if ($(this).is(':checked')) {
                                that.Element.find('input[type=checkbox]').prop("checked", true);
                            } else {
                                that.Element.find('input[type=checkbox]').prop("checked", false);
                            }
                        });

                    } else {
                        errorDialog(response.message);
                    }
                });
            }
        }

        this.Element.find("#proper-list-search-btn").click(function () {
            var table_name = that.Element.find("#table-name").val().trim();
            var column_key = that.Element.find("#column-key").val().trim();
            var column_name = that.Element.find("#column-name").val().trim();
            var where = that.Element.find("#table-where").val().trim().toLowerCase();
            if (table_name == "" || table_name == null) {
                warningDialog("表名不能为空");
                return false;
            }

            var keys = column_key.split(",");
            var names = column_name.split(",");
            if (keys.length != names.length) {
                warningDialog("名称和显示名称数量不相同");
                return false;
            }

            if (where.length > 0) {
                if (where.indexOf('=') >= 0 && where.indexOf('and') < 0) {
                    var field = where.split("=")[0].trim();
                    var first = field.substr(0, 1);
                    var last = field.substr(-1);
                    if (first != "`" || last != "`") {
                        warningDialog('字段设置使用MySQL 关键字符串 “`”');
                        return false;
                    }
                } else if (where.indexOf('and') >= 0 && where.indexOf('=') >= 0) {
                    var wheres = where.split("and");
                    for (var i = 0; i < wheres.length; i++) {
                        var field = wheres[i].split("=")[0].trim();
                        var first = field.substr(0, 1);
                        var last = field.substr(-1);
                        if (first != "`" || last != "`") {
                            warningDialog('字段设置使用MySQL 关键字符串 “`”');
                            return false;
                        }
                    }
                } else {
                    warningDialog('语法错误');
                    return false;
                }
            }

            var params = {};
            params.table_name = table_name;
            params.columns = "";
            for (var i = 0; i < keys.length; i++) {
                params.columns += keys[i];
                if (i != keys.length - 1) {
                    params.columns += ",";
                }
            }

            params.where = where;
            requestJson('../product-bom/get-datas-by-talbe-name-handler', params, true, function (response) {
                if (response.status == 0) {
                    var thead = that.Element.find("thead");
                    var tbody = that.Element.find("tbody");
                    thead.empty();
                    tbody.empty();
                    var html_thead = '<tr><th><input type="checkbox" class="check-box" id="checkAll"></th>';

                    var names = that.Element.find("#column-name").val().split(",");
                    var keys = that.Element.find("#column-key").val().split(",");
                    for (var k = 0; k < names.length; k++) {
                        var name = names[k];
                        if (name.toLowerCase() != "id") {
                            html_thead += "<th>" + name + "</th>";
                        }
                    }

                    html_thead += "</tr>";

                    thead.append($(html_thead));

                    for (var i = 0; i < response.data.length; i++) {
                        var item = response.data[i];
                        var html_tbody = '';
                        html_tbody += '<tr>';
                        var chk = '';
                        chk = '<td><input type="checkbox" class="check-box"  name="list-checkbox" ';

                        var data_items = new Array();

                        for (var m = 0; m < keys.length; m++) {
                            data_items.push({"key": keys[m], "name": names[m]});
                        }
                        for (var j = 0; j < data_items.length; j++) {
                            var column = data_items[j];
                            chk += ' data-' + column.key + '="' + item[column.key] + '"';
                        }

                        if (item['url'] != undefined) {
                            chk += ' data-url="' + item['url'] + '"';
                        }
                        chk += '></td>';

                        var td = '';
                        for (var j = 0; j < keys.length; j++) {
                            if (keys[j].toLowerCase() != "id") {
                                td += '<td>' + item[keys[j]] + '</td>';
                            }
                        }

                        html_tbody += chk + td + '</tr>';
                        tbody.append($(html_tbody));
                    }

                    addNewData(that);

                    that.Element.find("#checkAll").click(function () {
                        if ($(this).is(':checked')) {
                            that.Element.find('input[type=checkbox]').prop("checked", true);
                        } else {
                            that.Element.find('input[type=checkbox]').prop("checked", false);
                        }
                    });


                } else {
                    errorDialog(response.message);
                }
            });
        });
        if (this.ValueRule != undefined) addNewData(this);

    },
    saveValue: function () {
        if (!this.ValueRule) {
            this.ValueRule = {};
        }
        this.ValueRule.type = "list";

        var table_name = this.Element.find("#table-name").val();
        var column_key = this.Element.find("#column-key").val();
        var column_name = this.Element.find("#column-name").val();
        var where = this.Element.find("#table-where").val();

        var keys = column_key.split(",");
        var names = column_name.split(",");
        if (keys.length != names.length) {
            warningDialog("名称和显示名称数量不相同");
            return false;
        }

        this.ValueRule.table_name = table_name;
        this.ValueRule.where = where;

        if (!this.ValueRule.columns) {
            this.ValueRule.columns = new Array();
        }
        this.ValueRule.columns.length = 0;
        for (var i = 0; i < keys.length; i++) {
            this.ValueRule.columns.push({"key": keys[i], "name": names[i]});
        }


        if (this.ValueRule.value_ids) {
            this.ValueRule.value_ids.length = 0;
        } else {
            this.ValueRule.value_ids = new Array();
        }

        var checks = this.Element.find("#bom-property-rule-list-table").find("input[name='list-checkbox']:checkbox:checked");

        if (this.ValueRule.values) {
            this.ValueRule.values.length = 0;
        } else {
            this.ValueRule.values = new Array();
        }
        for (var i = 0; i < checks.length; i++) {
            var check = $(checks[i]);
            var value = "";
            for (var j = 0; j < this.ValueRule.columns.length; j++) {
                var column = this.ValueRule.columns[j];
                value += "\"" + column["key"] + "\"" + ":" + "\"" + check.attr("data-" + column["key"]) + "\"";
                if (j < this.ValueRule.columns.length - 1) {
                    value += ",";
                }
            }
            if (check.attr("data-url") != undefined) {
                value += "," + "\"url\"" + ":" + "\"" + check.attr("data-url") + "\"";
            }

            this.ValueRule.values.push(JSON.parse("{" + value + "}"));
            this.ValueRule.value_ids.push(check.attr("data-id"));
        }
        this.ValueRule.IsEdit = true;
        return this.ValueRule;
    },
    getValue: function () {
        return this.ValueRule;
    }
};

function addNewData(obj) {
    $("#is_new_add_a").remove();
    var category_id = '';
    var action = '';
    var table_name = obj.Element.find("#table-name").val();
    var where = obj.Element.find("#table-where").val();

    if (where.length > 0) {

        var where_str = where.toLowerCase();
        if (where_str.indexOf('and') >= 0) {
            var wheres = where_str.split('and');
            for (var k = 0; k < wheres.length; k++) {
                if (wheres[k].indexOf('data_category_id') >= 0) {
                    category_id = wheres[k].split('=')[1].trim();
                    break;
                }
            }
        } else {
            var wheres = where_str.split('=');
            for (var m = 0; m < wheres.length; m++) {
                if (wheres[m].indexOf('data_category_id') >= 0) {
                    category_id = wheres[m + 1].trim();
                    break;
                }
            }

        }

    }

    var actions = table_name.split('_');
    actions.splice(0, 2);

    for (var k = 0; k < actions.length; k++) {
        action += '-' + actions[k];
    }
    action = action.substr(1);
    if (action == "data") {
        action = 'base-data';
    }
    var html_a = '';
    html_a += '<a id="is_new_add_a" class="btn btn-primary putaway-icon" style="float: left"';
    if (category_id != '') {
        html_a += 'onclick=onNewModalEdit(\"' + action + '\",' + category_id + ')>';
    } else {
        html_a += 'onclick=onNewModalEdit(\"' + action + '\")>';
    }
    html_a += '<div class="btn-icon"></div><div class="btn-text">添加更多</div></a>';
    $(html_a).prependTo("#proBomPropertyListFooter");
    return true;
}